package com.gitee.deament.server.core.cli.db.str;

import cn.hutool.core.util.NumberUtil;
import com.gitee.deament.server.config.SystemConfig;
import com.gitee.deament.server.core.annotation.CliHander;
import com.gitee.deament.server.core.cli.AbstractCli;
import com.gitee.deament.server.core.data.ConnectData;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.util.List;

/**
 *
 * @author deament
 */
@CliHander(command="SELECT")
public class SELECTcli extends AbstractCli {

    @Override
    public void executeCli(ChannelHandlerContext channelHandlerContext, String command) {
        List<String> values= getValues(command);
        if(values.size()!=2){
            channelHandlerContext.channel().writeAndFlush(new TextWebSocketFrame("\"ERR wrong number of arguments for 'select' command\""));
            return ;
        }
        if(!NumberUtil.isInteger(values.get(1)) ){
            channelHandlerContext.channel().writeAndFlush(new TextWebSocketFrame("\"ERR invalid DB index\""));
            return ;
        }
        int index=Integer.parseInt(values.get(1));
        if(index<0){
            channelHandlerContext.channel().writeAndFlush(new TextWebSocketFrame("\"ERR invalid DB index\""));
            return ;
        }
        if(index>= SystemConfig.dbData.getDBIndexSize()){
            channelHandlerContext.channel().writeAndFlush(new TextWebSocketFrame("\"ERR invalid DB index\""));
            return ;
        }
        ConnectData.SELECT_DB_STORAGE.changeDB(index,channelHandlerContext.channel().id().asLongText());
        channelHandlerContext.channel().writeAndFlush(new TextWebSocketFrame("\"OK\""));
    }
}
